package org.jchains.receiver.gui;

import java.awt.Insets;
import java.awt.Toolkit;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JTextArea;
import javax.swing.ProgressMonitor;
import javax.swing.SwingWorker;

import org.jchains.internal.Util;
import org.jchains.receiver.Perm;
import org.jchains.receiver.PolicyFile;

public class UpdateTask extends SwingWorker<Void, Void> implements
		PropertyChangeListener {

	static boolean DEBUG = Boolean.parseBoolean(System.getProperty(
			"org.jchains.debug", "false"));
	ReceiverForm theComp = null;
	ProgressMonitor progressMonitor = null;
	PolicyFile pf = null;
	JButton jb;
	int anzahl = 0;
	JTextArea taskOutput;
	File theFile =null;

	public UpdateTask(ReceiverForm c, ProgressMonitor pm, File f, JButton _jb,PolicyFile _pf) {
		theComp = c;
		progressMonitor = pm;
		jb = _jb;
		pf = _pf;
		theFile = f;
		addPropertyChangeListener(this);
		taskOutput = new JTextArea(5, 20);
		taskOutput.setMargin(new Insets(5, 5, 5, 5));
		taskOutput.setEditable(false);

	}

	public void done() {
		Toolkit.getDefaultToolkit().beep();
		jb.setEnabled(true);
		progressMonitor.setNote("finished with ");
		int wait = 1500;
		Util.waitMillis(wait);
		progressMonitor.setProgress(100);

	}

	public Void doInBackground() {
		System.out.println("Import triggered");
		PermTableModel pt = (PermTableModel) theComp.getTabPermission()
				.getModel();
		int i = 0;
		// FileChannel f = null;
		setProgress(0);
		int progress = 0;

		FileInputStream f = null;
		try {
			f = new FileInputStream(theFile);
			// if (false) {
			// f = new FileInputStream("xxx.xxx").getChannel();

			// ObjectInputStream ois = new ObjectInputStream(Channels
			// .newInputStream(f));

			// } else {

			// FileInputStream is = new FileInputStream (f);
			// }

			// perms = new Vector<Perm>();
			//pf = new PolicyFile("", null);
			int lauf = 0;
			BufferedReader br = new BufferedReader(new InputStreamReader(f));
			boolean ende = false;
			int delta = 1;
			pt.setPerms(new Vector<Perm>(0));
			while (!ende) {
				progress += delta;
				setProgress(progress / 100);

				delta = deltaFromProgress(progress, delta);
				String z = br.readLine();

				Perm pp = null;

				try {

					pp = new Perm(z);

				} catch (Exception e) {
					if (DEBUG) {
						e.printStackTrace();
					}
					ende = true;
				}
				// if (pp instanceof Perm) {
				if (!ende) {
					pt.addPerm(pp);
					pf.add(pp);
					lauf++;
				} else {
					// System.out.println(pp.getClass() + ":" + pp);
				}
				i++;
				anzahl = i;
			}
			f.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				f.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		anzahl = i;
		pt.fireTableDataChanged();
		System.out.println("Import ended:" + i);
		progressMonitor.setNote("Import ended:" + i + " Permissions");
		
		
		return null;
	}

	private int deltaFromProgress(int progress, int delta) {
		if (progress == 10000) {
			delta = -1;
		} else if (progress == 0) {
			delta = 1;
		}
		return delta;
	}

	public void propertyChange(PropertyChangeEvent evt) {

		if ("progress" == evt.getPropertyName()) {
			int progress = (Integer) evt.getNewValue();
			progressMonitor.setProgress(progress);
			String message = String.format("Read : %d permissions.\n", anzahl);
			progressMonitor.setNote(message);
			taskOutput.append(message);
			// if (progressMonitor.isCanceled() || task.isDone()) {
			if (progressMonitor.isCanceled() || isDone()) {
				Toolkit.getDefaultToolkit().beep();
				if (progressMonitor.isCanceled()) {
					// task.cancel(true);
					cancel(true);
					taskOutput.append("Task canceled.\n");
				} else {
					taskOutput.append("Task completed.\n");
				}
				jb.setEnabled(true);
			}
		}

	}
}